// pages/rights-and-interests/opening-privilege/opening-privilege.js
import {http} from "../../../utils/http";
import {api} from "../../../utils/api";

let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    status: app.globalData.statusHeight, // 头部占位高度
    navHeight: app.globalData.navHeight, // 头部内容区
    backType:'back', // 返回类型，back,home
    list:[],
    listItem:{},
    isKCode:false, // 是否空code
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;

    if (options.isKCode){
      this.setData({
        isKCode:options.isKCode
      })
    }

    if (options) {
      // 卡片解析
      if (options.code) {
        app.store.setState({
          invite_code: options.code
            ? options.code
            : app.store.$state.invite_code,
        });
        that.setData({
          invite_code: options.code ? options.code : '',
          type: options.type ? options.type : '',
        });
      }
      if (options.type) {
        that.setData({
          type: options.type,
        });
      }
      // 二维码解析
      if (options.scene) {
        let scene = decodeURIComponent(options.scene);
        var arrPara = scene.split('&');
        var arr = [];
        for (var i in arrPara) {
          arr = arrPara[i].split('=');
          if (i == 0) {
            app.store.setState({
              invite_code: arr[1],
            });
            that.setData({
              invite_code: arr[1],
            });
          } else if (i == 1) {
            app.store.setState({
              uid: arr[1] ? arr[1] : '',
            });
            that.setData({
              uid: arr[1] ? arr[1] : '',
            });
          } else {
            that.setData({
              productId: arr[1] ? arr[1] : '',
            });
            app.store.setState({
              id: arr[1] ? arr[1] : '',
            });
          }
        }
      }
      if (that.data.invite_code) {
        that.setData({
          shareIt: 2,
        });
      }
    }

    console.log('options.code----',options.code);
    // 绑定邀请码
    console.log('绑定邀请码----')
    // this.bindInvitationCd();
    // this.bindCode({
    //   code:options.code
    // });
    if (app.globalData.checkLogin) {

      console.log('-------222222------------')
      console.log('getApp().store.$state.token---111111111---------',getApp().store.$state.token)
      console.log('---------999999999-----111-----------',getApp().store.$state.invite_code)
      // 如果上个页面传了空的code
      if (this.data.isKCode){
        this.volumeIndexGetList(); // 购物卷活动列表
      } else if (app.store.$state.invite_code) {
        that.bindInvitationCd();
        that.setData({
          shareIt: 2,
        });
        this.volumeIndexGetList(); // 购物卷活动列表
      }
    } else {
      app.checkLoginReadyCallback = (res) => {

        console.log('getApp().store.$state.token---222222222---------',getApp().store.$state.token)
        console.log('---------999999999------222----------',getApp().store.$state.invite_code)
        if (this.data.isKCode){
          this.volumeIndexGetList(); // 购物卷活动列表
        } else if (app.store.$state.invite_code) {
          that.bindInvitationCd();
          that.setData({
            shareIt: 2,
          });
          this.volumeIndexGetList(); // 购物卷活动列表
        }
        console.log('-------3333333333------------')
      };
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.topReturnBtn(); // 判断是否需要直接返回首页
    // this.aa();
    // 禁用分享
    wx.hideShareMenu({
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },

  // 绑定邀请码
  aa() {
    console.log('绑定邀请码---------------------绑定邀请码-------------')
    console.log('---------999999999----------------',getApp().store.$state.invite_code)
    console.log('---------7878787878----------------',getApp().store.$state.token)
    let that = this;
    http({
      url: api.post_my_bindInviteCode,
      data: {
        code: getApp().store.$state.invite_code,
      },
      header: {
        Authorization: getApp().store.$state.token,
      },
    })
      .then((res) => {
        console.log('--------------------res--565656565656565--',res)
        getApp().store.setState({
          shareIt: 1,
          invite_code: '',
        });
      })
      .catch((err) => {
        console.log('--------------------err--565656565656565--',err)
        getApp().store.setState({
          shareIt: 1,
          invite_code: '',
        });
      });
  },

  // 绑定邀请码
  // bindCode(param) {
  //   console.log('---------55555555555----------------',param.code)
  //   let that = this;
  //   app.http({
  //     url: api.post_my_bindInviteCode,
  //     data: {
  //       code: param.code,
  //     },
  //     header: {
  //       Authorization: getApp().store.$state.token,
  //     },
  //   })
  //     .then((res) => {
  //       console.log('res------------------',res);
  //       // getApp().store.setState({
  //       //   shareIt: 1,
  //       //   invite_code: '',
  //       // });
  //     })
  //     .catch((err) => {
  //       getApp().store.setState({
  //         shareIt: 1,
  //         invite_code: '',
  //       });
  //     });
  // },

  // 顶部返回按钮
  topReturnBtn() {
    let pages = getCurrentPages(); //获取所有页面
    // console.log('pages---',pages);
    // console.log('pages.length---',pages.length);
    if (pages.length <= 1){ // 返回类型，back,home
      this.setData({
        backType:'home'
      })
      // 返回首页
      // wx.switchTab({
      //   url: '/pages/index/index',
      // });
    } else {
      this.setData({
        backType:'back'
      })
      // 返回上一页
      // wx.navigateBack({
      //   delta: 1,
      // });
    }
  },

  // 获取特权列表
  volumeIndexGetList(){
    let that = this;

    console.log('app.store.$state.invite_code---',app.store.$state.invite_code)

    app.http({
      url: app.api.volumeIndexGetList,
      data: {
        code: getApp().store.$state.invite_code ? getApp().store.$state.invite_code : ''
      },
      //method: 'get',
    })
      .then((res) => {

        let requestData = res.data.data;
        console.log('res-----requestData--',requestData.page);
        // if (requestData.path > 0){

          // if (requestData.path == 1){
          //
          // } else {
          //   wx.reLaunch({
          //     url: requestData.page
          //   })
          // }
        // }
        wx.reLaunch({
          url: requestData.page
        });
        that.setData({
          list:requestData.list
        })
      })
      .catch((err) => {});
  },

  // 查看详情
  seeDetails(ev){
    let item = ev.currentTarget.dataset.item
    console.log("查看详情---item--",item);
    wx.navigateTo({
      url: '/pages/rights-and-interests/privilege-details/privilege-details?privilegeItem=' + JSON.stringify(item)
    })
  },

  clickRightBox(ev){
    console.log('clickRightBox------666---')
    let item = ev.currentTarget.dataset.item
    console.log('item',item)
    this.setData({
      listItem:item
    })
    // this.btn(ev)
  },

  // 购买按钮
  btn(ev) {
    let that = this;
    // console.log("item---", item);
    console.log('购买按钮---------------------',ev)
    console.log('购买按钮-------listItem--------------',this.data.listItem)

    // // 判断是否授权手机号
    // if (!this.data.$state.getPhoneNumber){
    //   app.store.setState({
    //     getPhoneNumber: true,
    //   });
    //   return ;
    // }

    let item = ev.currentTarget.dataset.item;
    app.http({
      url: app.api.post_my_rechargeVolume,
      data: {
        id: that.data.listItem.id ? that.data.listItem.id : item.id,
        // id: that.data.listItem.id,
        // code: that.data.invite_code,
      },
    })
      .then((res) => {
        that.setData({
          listItem:{},
        })
        wx.requestPayment({
          //调起支付
          //下边参数具体看微信小程序官方文档
          timeStamp: res.data.data.timeStamp,
          nonceStr: res.data.data.nonceStr,
          package: res.data.data.package,
          signType: res.data.data.signType,
          paySign: res.data.data.paySign,
          success(res) {
            // wx.requestSubscribeMessage({
            // 	tmplIds: [
            // 		'FddT6-1bVu2lfiggUR7FVmS0mwrvTlGIgksy6xh94XE',
            // 	],
            // 	success(res) {},
            // });
            // 微信支付ok 直接跳转到我的订单列表
            if (res.errMsg == 'requestPayment:ok') {
              wx.navigateTo({
                url:
                  '/pages/shoppingVolume/recordsOfConsumption/recordsOfConsumption',
              });
            }
          },
          fail(res) {},
        });
      })
      .catch((err) => {});
  },

  // bindTapPhoneNumber(){
  //   app.store.setState({
  //     login: true,
  //     getPhoneNumber: false,
  //     loginType: 2,
  //   });
  // },

  bindGetPhoneNumber(e) {
    console.log('e----',e);
    if (e.detail.iv) {
      app.store.setState({
        login: true,
        getPhoneNumber: false,
        loginType: 2,
      });
    } else {
      wx.showToast({
        title: '您取消了授权',
        icon: 'none',
        duration: 1500,
      });
    }
  },

  // 返回首页
  backHome(){
    wx.switchTab({
      url: '/pages/tabBar/index/index'
    })
  },

  bindGetUserInfo(ev){
    let item = ev.currentTarget.dataset.item;
    console.log('item---99---',item)
  },

  PhoneNumber(e) {
    console.log('PhoneNumber--eee--',e)
    let that = this;
    // 登录
    wx.login({
      success(res) {
        let header = {};
        if (res.code) {
          app.http({
            url: '/user/login/wxLogin',
            data: {
              code: res.code,
            },
            header: header,
          })
            .then((res) => {
              wx.setStorageSync('token', res.data.data.token);
              if (e.detail.iv) {
                app.http({
                  url: app.api.post_index_bindingPhone,
                  data: {
                    encryptedData: e.detail.encryptedData,
                    iv: e.detail.iv,
                  },
                })
                  .then((res) => {
                    app.store.setState({
                      login: true,
                      getPhoneNumber: false,
                      loginType: 2,
                    });
                    console.log('that.btn();------222--')
                    that.btn(e);
                  })
                  .catch((err) => {});
              } else {
                wx.showToast({
                  title: '您取消了授权',
                  icon: 'none',
                  duration: 1500,
                });
              }
            })
            .catch((err) => {});
        }
      },
      fail: (err) => {},
    });
  },

  // 立即开通
  openBtn(){
    console.log("立即开通---");
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    let that = this;
    // let invite_code = app.store.getState().infoData.invite_code;
    // let title = that.data.getVolume.title;
    // let share = that.data.getVolume.share;
    if (res.from === 'menu') {
      return {
        title: '特权',
        path: `/pages/rights-and-interests/opening-privilege/opening-privilege`,
        imageUrl: '',
        success() {},
        fail() {},
        complete() {},
      };
    }
    return;
  },
})
